package com.noble.library.third.TencentAI.face;

import com.noble.library.third.TencentAI.TencentAIUtil;
import com.noble.library.third.TencentAI.base.BaseClient;
import com.noble.library.third.TencentAI.http.TAipEBodyFormat;
import com.noble.library.third.TencentAI.http.TAipRequest;
import com.noble.library.third.TencentAI.sign.TencentAISignSort;
import com.noble.library.third.TencentAI.util.Base64Util;
import com.noble.library.third.TencentAI.util.FileUtil;
import com.noble.library.third.TencentAI.util.RandomNonceStrUtil;

/**
 * 计算机视觉人脸识别模块
 */
public class TAipFace extends BaseClient {

    public TAipFace(String app_id, String app_key) {
        super(app_id, app_key);
    }

    /**
     * 人脸检测与分析
     * 识别上传图像上面的人脸信息
     *
     * @param image - 二进制图像数据
     */
    public void detect(byte[] image, TencentAIUtil.TAiCallback callback) throws Exception {
        TAipRequest request = new TAipRequest();
        String time_stamp = System.currentTimeMillis() / 1000 + "";
        request.addBody("app_id", app_id);
        request.addBody("time_stamp", time_stamp);
        request.addBody("nonce_str", RandomNonceStrUtil.getRandomString());
        String base64Content = Base64Util.encode(image);
        request.addBody("image", base64Content);
        request.addBody("mode", "1");
        String sign = TencentAISignSort.getSignature(request.getBody(), app_key);
        request.addBody("sign", sign);
        request.setUri(FaceConsts.FACE_DETECT);
        request.setBodyFormat(TAipEBodyFormat.FORM_KV);
        requestServer(request, callback);
    }

    /**
     * 人脸检测与分析
     * 识别上传图像上面的人脸信息
     * 暂时不可以使用
     *
     * @param url - 图像网络地址
     */
    @Deprecated
    public void detectByUrl(String url, TencentAIUtil.TAiCallback callback) throws Exception {
        TAipRequest request = new TAipRequest();
        String time_stamp = System.currentTimeMillis() / 1000 + "";
        request.addBody("app_id", app_id);
        request.addBody("time_stamp", time_stamp);
        request.addBody("nonce_str", RandomNonceStrUtil.getRandomString());
        request.addBody("image_url", url);
        request.addBody("mode", "1");
        String sign = TencentAISignSort.getSignature(request.getBody(), app_key);
        request.addBody("sign", sign);
        request.setUri(FaceConsts.FACE_DETECT);
        request.setBodyFormat(TAipEBodyFormat.FORM_KV);
        requestServer(request, callback);
    }

    /**
     * 人脸检测与分析
     * 识别上传图像上面的人脸信息
     *
     * @param filePath - 本地路径图像文件
     */
    public void detect(String filePath, TencentAIUtil.TAiCallback callback) throws Exception {
        byte[] image = FileUtil.readFileByBytes(filePath);
        detect(image, callback);
    }
}
